using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using Isis.Interfaces;

namespace Isis.Model
{
    public class CacheWrapper : ICacheWrapper
    {
        public void ClearCache(Cache cache)
        {
            IEnumerable<string> keyList = GetCacheKeys(cache);
            foreach (string key in keyList)
            {
                cache.Remove(key);
            }
        }

        public IEnumerable<string> GetCacheKeys(Cache cache)
        {
            IList<string> keyList = new List<string>();
            IDictionaryEnumerator cacheEnum = cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                keyList.Add(cacheEnum.Key.ToString());
            }
            return keyList;
        }

        public IDictionary<string, object> GetCacheItems()
        {
            return HttpContext.Current.Cache.Cast<DictionaryEntry>().ToDictionary(foo => foo.Key.ToString(), foo => foo.Value);
        }

        public int GetCacheCount()
        {
            return HttpRuntime.Cache.Count;
        }

        public double GetMaxCacheMemoryPercentage()
        {
            long memoryLimit = HttpContext.Current.Cache.EffectivePercentagePhysicalMemoryLimit;

            return memoryLimit / 100.0;
        }

        public double GetMaxCacheMemory()
        {
            long effectivePrivateBytesLimit = HttpContext.Current.Cache.EffectivePrivateBytesLimit;

            if (effectivePrivateBytesLimit < 0)
            {
                return 0;
            }

            return effectivePrivateBytesLimit;
        }
    }
}